package top.healthylife.gateway.platform.zzc.api.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import top.healthylife.basics.utils.exception.BusinessException;
import top.healthylife.basics.utils.utils.SystemThreadLocal;
import top.healthylife.gateway.platform.zzc.api.config.SystemConfig;
import top.heathylife.gateway.common.cons.SystemCons;
import top.heathylife.gateway.common.po.RecordRequestInfo;

import java.util.HashMap;
import java.util.Map;


/**
 * [Description] : 请求外部接口的http请求工具类
 *
 * @author : zqs
 * @version : 1.0
 * @since : 2019-12-11 15:57
 */
@Slf4j
public class OutHttpUtil {

    final static String CODE = "0";
    final static String NOT_DATA = "300000";

    public final static String ERROR_CODE = "errorCode";
    public final static String ERROR_MESSAGE = "errorMessage";
    public final static String[] TOKEN_WRONG = {"ERR-10000","ERR-20001","ERR-20002","ERR-20003"};
    public static final Map<String, String> ERROR_MAP = new HashMap<>();

    static {
        ERROR_MAP.put("ERR-10000", "一般错误");
        ERROR_MAP.put("ERR-20001", "没有授权");
        ERROR_MAP.put("ERR-20002", "无访问权限");
        ERROR_MAP.put("ERR-20003", "余额不足");
        ERROR_MAP.put("ERR-30001", "姓名、身份证号、手机号缺失或无效");
        ERROR_MAP.put("ERR-30002", "家庭电话或工作电话无效");
        ERROR_MAP.put("ERR-30003", "家庭地址、工作地址或地址无效");
        ERROR_MAP.put("ERR-30004", "入参中的source的值缺失或无效");
        ERROR_MAP.put("ERR-30005", "子机构代码缺失或无效");
        ERROR_MAP.put("ERR-30006", "入参中的source中的值重复");
        ERROR_MAP.put("ERR-30007", "起始时间或结束时间缺失或无效");
        ERROR_MAP.put("ERR-30008", "起始时间和结束时间必须早于当前时间");
        ERROR_MAP.put("ERR-30009", "起始时间必须早于结束时间");
        ERROR_MAP.put("ERR-30010", "用于校验的手机号无效");
        ERROR_MAP.put("ERR-30011", "家庭地址缺失");
        ERROR_MAP.put("ERR-30012", "“月”字段缺失");
        ERROR_MAP.put("ERR-30013", "工作地址缺失");
        ERROR_MAP.put("ERR-30014", "“日期”字段缺失或无效");
        ERROR_MAP.put("ERR-30015", "部分入参(如身份证、手机号)缺失");
        ERROR_MAP.put("ERR-30016", "“贷款类型”字段缺失或无效");
    }

    /**
     * 发送get请求
     *
     * @param url    .
     * @param params 参数
     * @return 响应json
     */
    @SneakyThrows
    public static <T> T get(String url, Map<String, Object> params, SystemConfig systemConfig, Class<T> cls) {
        long l1 = System.currentTimeMillis();
        String body = JSONObject.toJSONString(params);
        Map<String, String> header = new HashMap<>(2);
        String token = systemConfig.getToken();
        header.put("Authorization", token);
        RecordRequestInfo.recordRequest(url, body, header, "post");
        String respContext = HttpRequest.post(url)
                .header("Authorization", token)
                .body(body)
                .execute().body();
        log.info("结果返回为,Url:{},params:{},result:{}", url, body, respContext);
//        String respContext = "{\"result\":{\"certificate\":{\"validityPeriod\":\"2021-05-10\",\"certNo\":\"D123456789\",\"companyName\":\"全维度测试有限责任公司\",\"certDate\":\"2019-02-22\",\"qualificationRange\":\"电子与智能化工程专业承包 贰级,防水防腐保温工程专业承包 贰级,建筑幕墙工程专业承包 贰级,建筑装修装饰工程专业承包 壹级,消防设施工程专业承包 贰级\"},\"qualification\":{\"organ\":\"北京市住房和城乡建设委员会\",\"effectiveTime\":\"2021-02-12\",\"issuingCertificateTime\":\"2018-02-13\",\"type\":\"建筑业企业资质\",\"certificateNum\":\"D123456789\",\"qualificationName\":\"建筑装修装饰工程专业承包二级\"}},\"reason\":\"ok\",\"error_code\":0}";
        long l2 = System.currentTimeMillis();
        //将三方元数据存储到线程变量
        SystemThreadLocal.set(SystemCons.ORIGIN_DATA,respContext);
        log.info("接口模块请求第三方耗时:{}", l2 - l1);
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(respContext);
        } catch (Exception e) {
            log.error("数据结构有异常,{}", respContext);
            throw new BusinessException("数据结构有异常");
        }
        String code = jsonObject.getString(ERROR_CODE);
        if (ObjectUtil.isNotEmpty(code)) {
            String message;
            if (ERROR_MAP.containsKey(code)) {
                message ="中智诚响应结果:"+ERROR_MAP.get(code);
            } else {
                message = jsonObject.getString(ERROR_MESSAGE);
                ERROR_MAP.put(code, message);
            }
            log.error("请求结果出错,错误原因:{},Url:{},params:{},result:{}", message, url, body, respContext);
            throw new BusinessException(message);

        }
        if (ObjectUtil.isNull(jsonObject)) {
            return null;
        }
        JSONObject blacklist = jsonObject.getJSONObject("blacklist");
        if (ObjectUtil.isNull(blacklist)) {
            return null;
        }
        return blacklist.toJavaObject(cls);
    }

}
